import { fileURLToPath, URL } from 'node:url'

import { ConfigEnv, loadEnv, ProxyOptions, UserConfigExport } from 'vite'
import vue from '@vitejs/plugin-vue'
import vueJsx from '@vitejs/plugin-vue-jsx'
import vueDevTools from 'vite-plugin-vue-devtools'
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'
import { ComponentResolveResult } from 'unplugin-vue-components'
import tailwindcss from '@tailwindcss/vite'

export default ({ mode }: ConfigEnv): UserConfigExport => {
    const env = loadEnv(mode, process.cwd())
    return {
        base: env.VITE_BASE_URL,
        logLevel: 'warn', // 可选值：'info'（默认）| 'warn' | 'error' | 'silent'
        plugins: [
            tailwindcss(),
            vue(),
            vueJsx(),
            vueDevTools(),
            AutoImport({
                resolvers: [ElementPlusResolver()],
                // 目标文件
                include: [
                    /\.[tj]sx?$/, // .ts, .tsx, .js, .jsx
                    /\.vue$/,
                    /\.vue\?vue/, // .vue
                    /\.md$/ // .md
                ],

                // 全局引入插件
                imports: [
                    // presets
                    'vue',
                    'vue-router',
                    'vue-i18n',
                    // custom
                    {
                        '@vueuse/core': [
                            // named imports
                            'useMouse', // import { useMouse } from '@vueuse/core',
                            // alias
                            ['useFetch', 'useMyFetch'] // import { useFetch as useMyFetch } from '@vueuse/core',
                        ],
                        axios: [
                            // default imports
                            ['default', 'axios'] // import { default as axios } from 'axios',
                        ],
                        '[package-name]': [
                            // '[import-names]',
                            // alias
                            ['[from]', '[alias]']
                        ]
                    }
                ],

                // eslint报错解决
                eslintrc: {
                    enabled: true, // Default `false`
                    filepath: './.eslintrc-auto-import.json', // Default `./.eslintrc-auto-import.json`
                    globalsPropValue: true // Default `true`, (true | false | 'readonly' | 'readable' | 'writable' | 'writeable')
                },
                // 声明文件生成位置和文件名称
                dts: './auto-imports.d.ts'
            }),
            Components({
                resolvers: [
                    (name: string): ComponentResolveResult | null => {
                        if (name.startsWith('kitego')) {
                            return {
                                name: name.toLowerCase(),
                                from: `@/components/${name.toLowerCase()}`
                            }
                        }
                    },
                    ElementPlusResolver()
                ]
            })
        ],
        resolve: {
            alias: {
                '@': fileURLToPath(new URL('./src', import.meta.url))
            }
        },
        optimizeDeps: {
            include: ['amis-editor-core']
        },
        server: {
            host: '0.0.0.0',
            port: Number(env.VITE_VUE_PORT),
            open: true,
            cors: true,
            proxy: createProxy(JSON.parse(env.VITE_PROXY || '[]')),
            warmup: {
                clientFiles: ['./index.html', './src/{views,components}/*']
            }
        },
        // 设置 public 目录
        publicDir: 'public',
        build: {
            emptyOutDir: true, // 确保每次构建清空dist
            outDir: 'dist',
            minify: 'esbuild',
            // esbuild 打包更快，但是不能去除 console.log。terser打包慢，但能去除 console.log，正式环境建议使用
            // minify: "terser",
            // terserOptions: {
            // 	compress: {
            // 		drop_console: viteEnv.VITE_DROP_CONSOLE,
            // 		drop_debugger: true
            // 	}
            // },
            // 规定触发警告的 chunk 大小
            chunkSizeWarningLimit: 2000,
            rollupOptions: {
                output: {
                    entryFileNames: `assets/[name].[hash].js`,
                    chunkFileNames: `assets/[name].[hash].js`,
                    assetFileNames: `assets/[name].[hash].[ext]`,
                    manualChunks(id) {
                        if (id.includes('node_modules')) {
                            return id.toString().split('node_modules/')[1].split('/')[0].toString()
                        }
                    }
                }
            }
        }
    }
}

type ProxyItem = [string, string]

type ProxyList = ProxyItem[]

type ProxyTargetList = Record<string, ProxyOptions>

/**
 * 创建代理，用于解析 .env.development 代理配置
 * @param list
 */
function createProxy(list: ProxyList = []) {
    const ret: ProxyTargetList = {}
    for (const [prefix, target] of list) {
        const httpsRE = /^https:\/\//
        const isHttps = httpsRE.test(target)

        // https://github.com/http-party/node-http-proxy#options
        ret[prefix] = {
            target: target,
            changeOrigin: true,
            ws: true,
            rewrite: (path: any) => path.replace(new RegExp(`^${prefix}`), ''),
            // https is require secure=false
            ...(isHttps ? { secure: false } : {})
        }
    }
    return ret
}
